#include "Kernel.h"
#include "SortedMemoryStack.h"

typedef SortedMemoryStackNode_s SortedMemoryStackNode_t;

struct SortedMemoryStackNode_s
{
	union
	{
		Address fAddress;
		SortedMemoryStackNode_t * fNext;
	};
}
_PACKED;


CSortedMemoryStack::CSortedMemoryStack()
{
	fFirst = NULL;
	fCount = 0;
}

CSortedMemoryStack::~CSortedMemoryStack()
{
	fFirst = NULL;
	fCount = 0;
}

void CSortedMemoryStack::Push( void * memory )
{
	if( memory == NULL )
		return;

	Address address = (Address)memory;
	SortedMemoryStackNode * node = (SortedMemoryStackNode *)memory;
	SortedMemoryStackNode * next = fFirst;
	SortedMemoryStackNode * prev = NULL;

	while( next != NULL )
	{
		if( next->fAddress > address )
			break;

		prev = node;
		next = next->fNext;
	}

	if( prev != NULL )
		prev->fNext = node;

	node->fNext = next;

	if( fFirst == NULL || fFirst == next )
		fFirst = node;

	fCount++;
}

void * CSortedMemoryStack::Pop( void )
{
	if( fFirst == NULL || fCount == 0 )
		return NULL;

	SortedMemoryStackNode * first = fFirst;

	fFirst = fFirst->fNext;
	fCount--;

	return first;
}
